package web.PetStore.web.servlet;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

@WebServlet(name = "/CaptchaServlet", urlPatterns = {"/Captcha"})
public class CaptchaServlet extends HttpServlet {
    private static final String STR = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    private static final String[] FONT_NAME =
            {"黑体", "宋体", "楷体", "Times New Roman", "Arial"};
    private static final Integer[] FONT_STYLE =
            {Font.PLAIN, Font.BOLD, Font.ITALIC, Font.BOLD + Font.PLAIN, Font.BOLD + Font.ITALIC,
                    Font.PLAIN + Font.ITALIC, Font.BOLD + Font.PLAIN + Font.ITALIC};
    private static final int WIDTH = 150;
    private static final int HEIGHT = 40;
    private static String captcha;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //初始化验证码及绘图工具
        BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
        Graphics2D g = image.createGraphics();

        //背景
        g.setColor(new Color(168, 168, 168));
        g.fillRect(0, 0, WIDTH, HEIGHT);
        g.setColor(Color.BLACK);
        g.drawRect(0, 0, WIDTH, HEIGHT);

        StringBuilder ans = new StringBuilder();
        Random ran = new Random();

        //绘制字符
        for (int i = 0;i < 4;i++){
            //随机样式
            g.setFont(new Font(FONT_NAME[ran.nextInt(5)], FONT_STYLE[ran.nextInt(7)], 28));

            //随机字符
            char ch = STR.charAt(ran.nextInt(36));
            ans.append(ch);

            //四个字符在指定区域随机生成
            g.drawString(ch+"",ran.nextInt(22) + 6 + i * 30, ran.nextInt(15) + 25);
        }

        //绘制干扰线
        for (int i = 0;i < 7;i++){
            g.drawLine(ran.nextInt(130) + 10, ran.nextInt(30) + 5,ran.nextInt(130) + 10,ran.nextInt(30) + 5);
        }

        //答案放在静态变量中
        captcha = ans.toString();

        //图片形式返回get请求
        ImageIO.write(image, "jpg", resp.getOutputStream());
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req,resp);
    }

    //检查验证码
    public static boolean checkCodeCorrect(String checkcode){
        if(checkcode.length() != captcha.length()){
            return false;
        }
        return checkcode.toUpperCase().equals(captcha);
    }
}
